import java.io.*;
import java.net.Socket;

public class ChatChannel implements Runnable{
    private Socket socket;
    private ObjectInputStream ois;
    private ObjectOutputStream oos;
    private String name;

    public ChatChannel(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            recvNameAndEchoHello();

            while (true){
                String msg= (String) ois.readObject();
                System.out.println(name+"说:"+msg);
                oos.writeObject(name+"说："+msg);
                oos.flush();
            }
        }
        catch(IOException e){
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void recvNameAndEchoHello() throws IOException, ClassNotFoundException {
        InputStream is = socket.getInputStream();
        ois = new ObjectInputStream(is);
        name = (String) ois.readObject();
        System.out.println(name + "进入聊天室");
        OutputStream os = socket.getOutputStream();
        oos = new ObjectOutputStream(os);
        oos.writeObject(name + ",您好！欢迎您进入聊天室");
    }
}

